# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/6/18
# @File   : R23_IC_EnforcementRecordCheck_XD.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:申请人强制执行、行政处罚记录校验
code:R23_IC_EnforcementRecordCheck_XD
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y%m%d')\
                    for i in range(6)]


def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None


def isfloat(x):

    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False



# 获取 上次申请时间
def get_relative_date():
    relative_date = ratingRequest.get('relativeDate')
    return formatDate(relative_date)


def EnforcementRecordCheck1():
    ICRForceExecution = getTable('ICRForceExecution')
    if ICRForceExecution is None:
        return None
    elif ICRForceExecution == [{}]:
        return 1
    else:
        relativeDate = get_relative_date()
        if relativeDate is None:
            raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
        Factor = []

        for i in ICRForceExecution:
            try:
                registerDate = i['registerDate']
                enforceMoney = i.get('enforceObjectMoney')
                if enforceMoney in null_type_list or not isfloat(enforceMoney):
                    enforceMoney = i['alreadyEnforceObjectMoney']

                if formatDate(registerDate) is not None and isfloat(enforceMoney) and formatDate(registerDate) <= last_year_list[0] \
                        and isfloat(enforceMoney) != 0 :
                    # 限定 立案日期  在上次申请时间到本次申请时间之前
                    if formatDate(registerDate) >  relativeDate:
                        registerDate = formatDate(registerDate)
                        if last_year_list[2] <= registerDate <= last_year_list[0] and float(enforceMoney) >= 6000:
                            Factor.append(u'拒绝')
                        elif last_year_list[3] <= registerDate < last_year_list[2] and float(enforceMoney) > 15000:
                            Factor.append(u'拒绝')
                        elif last_year_list[5] <= registerDate < last_year_list[3] and float(enforceMoney) > 25000:
                            Factor.append(u'拒绝')
                        else:
                            Factor.append(u'通过')
                else:
                    Factor.append(u'人工')
            except:
                Factor.append(u'人工')


        if u'拒绝' in Factor:
            return 0
        elif u'人工' in Factor:
            return 2
        else:
            return 1


def EnforcementRecordCheck2():
    ICRAdminPunishment = getTable('ICRAdminPunishment')
    if ICRAdminPunishment is None:
        return None
    elif ICRAdminPunishment == [{}]:
        return 1
    else:
        Factor = []
        relativeDate = get_relative_date()
        if relativeDate is None:
            raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
        for i in ICRAdminPunishment:
            try:
                beginDate = i['beginDate']
                money = i['money']

                if formatDate(beginDate) is not None and isfloat(money) and formatDate(beginDate) <= \
                        last_year_list[0] \
                        and isfloat(money) != 0:
                    # 限定时间范围为 生效日期 在 上一次申请日期 到 当前申请日期之间的
                    if formatDate(beginDate) > relativeDate:
                        beginDate = formatDate(beginDate)
                        if last_year_list[2] <= beginDate <= last_year_list[0] and float(money) >= 6000:
                            Factor.append(u'拒绝')
                        elif last_year_list[3] <= beginDate < last_year_list[2] and float(money) > 15000:
                            Factor.append(u'拒绝')
                        elif last_year_list[5] <= beginDate < last_year_list[3] and float(money) > 25000:
                            Factor.append(u'拒绝')
                        else:
                            Factor.append(u'通过')
                else:
                    Factor.append(u'人工')
            except:
                Factor.append(u'人工')

        if u'拒绝' in Factor:
            return 0
        elif u'人工' in Factor:
            return 2
        else:
            return 1

def R23_IC_EnforcementRecordCheck_XD():
    Factor1 = EnforcementRecordCheck1()
    Factor2 = EnforcementRecordCheck2()

    if Factor1 is None and Factor2 is None:
        return u'缺失值'
    elif Factor1 == 0 or Factor2 == 0:
        return 0
    elif Factor1 == 2 or Factor2 == 2:
        return 0
    else:
        return 1


result = R23_IC_EnforcementRecordCheck_XD()


if __name__ == '__main__':

    import json
    ratingRequest = {"legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511", "creditCode": "123456",
                     "regNumber": "12345", "relativeDate":u'2016/08/09'}
    file_obj = open(r'E:\\HQDIndicators\\testFiles\\IC_DSJ2.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False).get('IC_DSJ')
    aa = R23_IC_EnforcementRecordCheck_XD()
    print aa